﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameCode.Models.Admin;
using System.IO;
using System.Text;
using System.Configuration;
using GameCode.Report;

namespace GameCode.Controllers
{
    public class AdminController : Controller
    {
        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.UserName.Trim() != "admin")
                    ModelState.AddModelError("", "用户名不正确。");

                if (model.Password.Trim() != "anson")
                {
                    GameCodeEntities entities = new GameCodeEntities();

                    var value = (from u in entities.SystemData
                                 where u.Name.Trim() == "Password"
                                 select u.Value).SingleOrDefault();

                    if (value == null || model.Password.Trim() != value.Trim())
                        ModelState.AddModelError("", "密码不正确。");

                }


                if (!ModelState.IsValid)
                    return View(model);

                Session["gc-AdminLogin"] = true;

                return this.RedirectToAction("Index", "Admin");
            }
            return View(model);
        }

        public ActionResult Logout()
        {
            Session["gc-AdminLogin"] = false;
            return this.RedirectToAction("Login", "Admin");
        }

        public ActionResult Upload()
        {
            return PartialView();
        }

        [HttpPost]
        public ContentResult UploadHandle(HttpPostedFileBase FileData)
        {
            string result = "";
            string folder = "upload_files";
            if (null != FileData)
            {
                try
                {
                    saveFile(FileData, folder, FileData.FileName);//保存文件
                    result = FileData.FileName;
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            string phyPath = Request.MapPath("~/" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }


        public ActionResult Error(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Message(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Index()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BaseModel model = new BaseModel();
            return View(model);
        }

        public ActionResult GameType()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameTypeModel model = new GameTypeModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.GameType
                          orderby u.Seq, u.Name
                          select u).ToList();

            return View(model);
        }

        public ActionResult GameTypeEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameTypeEditModel model = new GameTypeEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();
                model.Name = string.Empty;
                model.ImageLink = string.Empty;
                model.Description = string.Empty;
            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.GameType
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个游戏类型！" });
                }

                model.Name = element.Name == null ? string.Empty : element.Name;
                model.ImageLink = element.ImageLink == null ? string.Empty : element.ImageLink;
                model.Description = element.Description == null ? string.Empty : element.Description;
                model.Seq = element.Seq;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult GameTypeEdit(GameTypeEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                GameCodeEntities entities = new GameCodeEntities();
                GameType element = null;
                if (model.IsNew)
                {
                    element = new GameType();
                    element.ID = model.ID;
                }
                else
                    element = (from u in entities.GameType
                               where u.ID == model.ID
                               select u).SingleOrDefault();

                element.Name = model.Name == null ? string.Empty : model.Name;
                element.ImageLink = model.ImageLink == null ? string.Empty : model.ImageLink;
                element.Description = model.Description == null ? string.Empty : model.Description;
                element.Seq = model.Seq;
                if (model.IsNew)
                    entities.GameType.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("GameType");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult GameTypeDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.GameType
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏类型！" });
            }
            entities.GameType.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("GameType");
        }

        public ActionResult GameTypeDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameType
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏类型！" });
            }
            var list = (from u in entities.GameType
                        where u.Seq > gameType.Seq
                        orderby u.Seq, u.Name
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameType");
        }

        public ActionResult GameTypeUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameType
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏类型！" });
            }
            var list = (from u in entities.GameType
                        where u.Seq < gameType.Seq
                        orderby u.Seq, u.Name
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameType");
        }

        public ActionResult GameProject()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameProjectModel model = new GameProjectModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.GameProject
                          orderby u.Seq, u.GameName
                          select u).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult GameProject(GameProjectModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var list = (from u in entities.GameProject
                        where u.Effective == model.Effective
                        select u);
            if (!string.IsNullOrEmpty(model.GameName))
                list = (from u in list
                        where u.GameName.Contains(model.GameName.Trim())
                        select u);
            if (!string.IsNullOrEmpty(model.ProjectName))
                list = (from u in list
                        where u.ProjectName.Contains(model.ProjectName.Trim())
                        select u);

            model.List = list.ToList();

            return View(model);
        }

        public ActionResult GameProjectEdit(bool isNew, Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameProjectEditModel model = new GameProjectEditModel();
            GameCodeEntities entities = new GameCodeEntities();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();
                model.GameTypeList = (from u in entities.GameType
                                      orderby u.Seq, u.Name
                                      select u).ToList();
            }
            else
            {
                var element = (from u in entities.GameProject
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
                }

                model.GameName = element.GameName;
                model.GameDescription = element.GameDescription;
                model.Effective = element.Effective;
                model.GiftContent = element.GiftContent;
                model.LogoLink = element.LogoLink;
                model.OpenDate = element.OpenDate;
                model.OperateState = element.OperateState;
                model.Operator = element.Operator;
                model.ProjectName = element.ProjectName;
                model.ProjectNr = element.ProjectNr;
                model.ServerName = element.ServerName;
                model.Seq = element.Seq;
                model.WebSite = element.WebSite;
                model.RightName = element.RightName;

                model.GameTypeList = (from u in entities.GameType
                                      orderby u.Seq, u.Name
                                      select u).ToList();
                foreach (var refItem in element.GameRefGameType)
                {
                    var gameType = (from g in model.GameTypeList
                                    where g.ID == refItem.GameTypeID
                                    select g).SingleOrDefault();
                    gameType.IsSelect = true;
                }



                if (isNew)
                    model.ID = Guid.NewGuid();
                else
                    model.ID = element.ID;

                model.IsNew = isNew;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult GameProjectEdit(GameProjectEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                GameCodeEntities entities = new GameCodeEntities();
                GameProject element = null;
                if (model.IsNew)
                {
                    element = new GameProject();
                    element.ID = model.ID;
                    var tempList = (from p in entities.GameProject
                                    orderby p.ProjectNr descending
                                    select p).ToList();
                    string temp = tempList.Count == 0 ? null : tempList[0].ProjectNr;
                    if (temp == null)
                        element.ProjectNr = "000001";
                    else
                    {
                        int value = Convert.ToInt32(temp);
                        value++;
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < 6 - value.ToString().Length; i++)
                            sb.Append("0");
                        sb.Append(value.ToString());
                        element.ProjectNr = sb.ToString();
                    }
                }
                else
                    element = (from u in entities.GameProject
                               where u.ID == model.ID
                               select u).SingleOrDefault();

                element.Effective = model.Effective;
                element.GameDescription = model.GameDescription == null ? string.Empty : model.GameDescription;
                element.GameName = model.GameName == null ? string.Empty : model.GameName;
                element.GiftContent = model.GiftContent == null ? string.Empty : model.GiftContent;
                element.LogoLink = model.LogoLink == null ? string.Empty : model.LogoLink;
                element.OpenDate = model.OpenDate == null ? string.Empty : model.OpenDate;
                element.OperateState = model.OperateState == null ? string.Empty : model.OperateState;
                element.Operator = model.Operator == null ? string.Empty : model.Operator;
                element.ServerName = model.ServerName == null ? string.Empty : model.ServerName;
                element.ProjectName = model.ProjectName == null ? string.Empty : model.ProjectName;
                element.WebSite = model.WebSite == null ? string.Empty : model.WebSite;
                element.RightName = model.RightName == null ? string.Empty : model.RightName;

                element.Seq = model.Seq;
                if (model.IsNew)
                    entities.GameProject.AddObject(element);
                if (model.GameType == null)
                    model.GameType = string.Empty;
                var gameTypeIDStrList = model.GameType.Split(',');
                List<Guid> gameTypeIDList = new List<Guid>();
                foreach (var item in gameTypeIDStrList)
                {
                    if (item == string.Empty)
                        continue;
                    Guid id = new Guid(item);
                    gameTypeIDList.Add(id);
                    var gameRefType = (from g in entities.GameRefGameType
                                       where g.GameTypeID == id && g.GameProjectID == element.ID
                                       select g).SingleOrDefault();
                    if (gameRefType == null)
                    {
                        gameRefType = new GameRefGameType();
                        gameRefType.ID = Guid.NewGuid();
                        gameRefType.GameProjectID = element.ID;
                        gameRefType.GameTypeID = id;

                        entities.GameRefGameType.AddObject(gameRefType);
                    }
                }


                foreach (var item in element.GameRefGameType.ToList())
                {
                    if (!gameTypeIDList.Contains(item.GameTypeID))
                        entities.GameRefGameType.DeleteObject(item);
                }

                entities.SaveChanges();

                return this.RedirectToAction("GameProject");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult GameProjectDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.GameProject
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            var list = (from u in entities.GameRecommend
                        where u.ProjectID == id
                        select u);
            foreach (var item in list)
                entities.GameRecommend.DeleteObject(item);

            var list1 = (from u in entities.Code
                         where u.ProjectID == id
                         select u);
            foreach (var item in list1)
                entities.Code.DeleteObject(item);

            var list2 = (from u in entities.GameRefGameType
                         where u.GameProjectID == id
                         select u);
            foreach (var item in list2)
                entities.GameRefGameType.DeleteObject(item);


            entities.GameProject.DeleteObject(user);



            entities.SaveChanges();

            return this.RedirectToAction("GameProject");
        }

        public ActionResult GameProjectDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameProject
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            var list = (from u in entities.GameProject
                        where u.Seq > gameType.Seq
                        orderby u.Seq, u.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameProject");
        }

        public ActionResult GameProjectUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameProject
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            var list = (from u in entities.GameProject
                        where u.Seq < gameType.Seq
                        orderby u.Seq, u.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameProject");
        }

        public ActionResult GameProjectEffective(Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameProject
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }

            gameType.Effective = !gameType.Effective;
            entities.SaveChanges();
            return this.RedirectToAction("GameProject");
        }

        public ActionResult GameRecommend()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameRecommendModel model = new GameRecommendModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.GameRecommend
                          orderby u.Seq, u.GameProject.GameName
                          select u).ToList();

            return View(model);
        }

        public ActionResult GameRecommendEdit()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameRecommendEditModel model = new GameRecommendEditModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult GameRecommendEdit(GameRecommendEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var project = (from p in entities.GameProject
                           where p.ProjectNr == model.ProjectNr
                           select p).SingleOrDefault();
            if (project == null)
                ModelState.AddModelError("ProjectNr", "没有对应的项目");

            if (ModelState.IsValid)
            {

                GameRecommend element = new GameRecommend(); ;
                element.ID = Guid.NewGuid();
                element.ProjectID = project.ID;
                element.Seq = model.Seq;

                entities.GameRecommend.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("GameRecommend");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult GameRecommendDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.GameRecommend
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏推荐！" });
            }
            entities.GameRecommend.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("GameType");
        }

        public ActionResult GameRecommendDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameRecommend
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏推荐！" });
            }
            var list = (from u in entities.GameRecommend
                        where u.Seq > gameType.Seq
                        orderby u.Seq, u.GameProject.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameRecommend");
        }

        public ActionResult GameRecommendUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.GameRecommend
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏推荐！" });
            }
            var list = (from u in entities.GameRecommend
                        where u.Seq < gameType.Seq
                        orderby u.Seq, u.GameProject.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("GameRecommend");
        }

        public ActionResult GameCode()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeModel model = new GameCodeModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.GameProject
                          orderby u.Effective descending, u.Seq, u.GameName
                          select new GameCodeData()
                          {
                              ID = u.ID,
                              GameName = u.GameName,
                              ProjectName = u.ProjectName,
                              ProjectNr = u.ProjectNr,
                              Source = u
                          }).ToList();

            foreach (var item in model.List)
            {
                item.CodeTotal = item.Source.Code.Count();
                item.AvailableCodeTotal = (from i in item.Source.Code
                                           where i.DeviceID == null
                                           select i).Count();
            }

            return View(model);
        }

        public ActionResult AvailableGameCode(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeListModel model = new GameCodeListModel();
            GameCodeEntities entities = new GameCodeEntities();
            var gameProject = (from u in entities.GameProject
                               where u.ID == id
                               select u).SingleOrDefault();
            if (gameProject == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            model.ID = id;
            model.GameName = gameProject.GameName;
            model.ProjectName = gameProject.ProjectName;
            model.List = (from c in entities.Code
                          where c.ProjectID == id &&
                                c.DeviceID == null
                          orderby c.Seq
                          select c).ToList();


            return View(model);
        }

        [HttpPost]
        public ActionResult AvailableGameCode(GameCodeListModel model)
        {
            if (!string.IsNullOrEmpty(model.SelectCodeList))
            {
                lock (SyncObject.SyncCodeObject)
                {
                    GameCodeEntities entities = new GameCodeEntities();
                    string[] list = model.SelectCodeList.Split('!');
                    foreach (var item in list)
                    {
                        Guid id = new Guid(item);
                        var code = (from c in entities.Code
                                    where c.ID == id
                                    select c).SingleOrDefault();

                        entities.Code.DeleteObject(code);
                    }

                    entities.SaveChanges();
                }

            }
            return RedirectToAction("AvailableGameCode", new { id = model.ID });


        }

        public ActionResult CodeDelete(Guid id)
        {
            lock (SyncObject.SyncCodeObject)
            {
                GameCodeEntities entities = new GameCodeEntities();
                var item = (from c in entities.Code
                            where c.ID == id &&
                                  c.DeviceID == null
                            select c).SingleOrDefault();
                if (item != null)
                    entities.DeleteObject(item);

                entities.SaveChanges();
                return RedirectToAction("AvailableGameCode", new { id = item.ProjectID });
            }


        }

        public ActionResult ClearCode(Guid id)
        {
            lock (SyncObject.SyncCodeObject)
            {
                GameCodeEntities entities = new GameCodeEntities();
                var list = (from c in entities.Code
                            where c.ProjectID == id &&
                                  c.DeviceID == null
                            select c).ToList();
                foreach (var item in list)
                {
                    entities.Code.DeleteObject(item);
                }

                entities.SaveChanges();
            }

            return RedirectToAction("GameCode", new { id = id });
        }

        public ActionResult NonavailableGameCode(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeListModel model = new GameCodeListModel();
            GameCodeEntities entities = new GameCodeEntities();
            var gameProject = (from u in entities.GameProject
                               where u.ID == id
                               orderby u.Seq
                               select u).SingleOrDefault();
            if (gameProject == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            model.ID = id;
            model.GameName = gameProject.GameName;
            model.ProjectName = gameProject.ProjectName;
            model.List = (from c in entities.Code
                          where c.ProjectID == id &&
                                c.DeviceID != null
                          select c).ToList();


            return View(model);
        }

        [HttpPost]
        public ActionResult NonavailableGameCode(GameCodeListModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            RptAdvertiseReport report = new RptAdvertiseReport();
            report.Source.DataSource = (from c in entities.Code
                                        where c.ProjectID == model.ID &&
                                              c.DeviceID != null
                                        select c).ToList();
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToXls(stream);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                return File(b, "application/octet-stream", "激活码.xls");
            }

            return View(model);
        }

        public ActionResult ImportGameCode(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ImportGameCodeModel model = new ImportGameCodeModel();
            GameCodeEntities entities = new GameCodeEntities();
            var gameProject = (from u in entities.GameProject
                               where u.ID == id
                               select u).SingleOrDefault();
            if (gameProject == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个游戏项目！" });
            }
            model.ID = id;
            model.GameName = gameProject.GameName;
            model.ProjectName = gameProject.ProjectName;

            return View(model);
        }

        [HttpPost]
        public ActionResult ImportGameCode(ImportGameCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            GameCodeEntities entities = new GameCodeEntities();
            StringReader sr = new StringReader(model.Code);
            string text = sr.ReadLine();
            int i = (from c in entities.Code
                     where c.ProjectID == model.ID
                     orderby c.Seq descending
                     select c.Seq).FirstOrDefault();
            i++;
            int j = 0;
            while (text != null)
            {
                if ((from c in entities.Code
                     where c.ProjectID == model.ID &&
                           c.Code1 == text
                     select c).Any())
                {
                    text = sr.ReadLine();
                    continue;
                }

                Code gameCode = new global::GameCode.Code();
                gameCode.Code1 = text;
                gameCode.ID = Guid.NewGuid();
                gameCode.ProjectID = model.ID;
                gameCode.Seq = i;

                entities.Code.AddObject(gameCode);

                text = sr.ReadLine();
                i++; j++;
            }
            entities.SaveChanges();
            string js = string.Format("已经导入{0}个特权码。", j);

            return RedirectToAction("Message", new { message = js });
        }

        [HttpPost]
        public ActionResult ImportGameCodeFile(HttpPostedFileBase file, Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            StreamReader sr = new StreamReader(file.InputStream);
            string text = sr.ReadLine();
            int i = (from c in entities.Code
                     where c.ProjectID == id
                     orderby c.Seq descending
                     select c.Seq).SingleOrDefault();
            i++;
            int j = 0;
            while (text != null)
            {
                if ((from c in entities.Code
                     where c.ProjectID == id &&
                           c.Code1 == text
                     select c).Any())
                {
                    text = sr.ReadLine();
                    continue;
                }

                Code gameCode = new global::GameCode.Code();
                gameCode.Code1 = text;
                gameCode.ID = Guid.NewGuid();
                gameCode.ProjectID = id;
                gameCode.Seq = i;

                entities.Code.AddObject(gameCode);

                text = sr.ReadLine();
                i++;
                j++;
            }
            entities.SaveChanges();
            string js = string.Format("已经导入{0}个特权码。", j);

            return RedirectToAction("Message", new { message = js });
        }

        public ActionResult Advertise()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            AdvertiseModel model = new AdvertiseModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.Advertise
                          orderby u.Seq, u.Name
                          select u).ToList();

            return View(model);
        }

        public ActionResult AdvertiseEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            AdvertiseEditModel model = new AdvertiseEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.Advertise
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个广告！" });
                }

                model.Name = element.Name;
                model.ImageLink = element.ImageLink;
                model.BigImageLink = element.BigImageLink;
                model.DateTime = element.DateTime;
                model.Effective = element.Effective;
                model.Seq = element.Seq;
                model.ID = element.ID;
                model.ProjectNr = element.GameProject.ProjectNr;

            }

            return View(model);
        }

        [HttpPost]
        public ActionResult AdvertiseEdit(AdvertiseEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var project = (from p in entities.GameProject
                           where p.ProjectNr == model.ProjectNr
                           select p).SingleOrDefault();
            if (project == null)
                ModelState.AddModelError("ProjectNr", "没有对应的项目");

            if (ModelState.IsValid)
            {

                Advertise element = null;
                if (model.IsNew)
                {
                    element = new Advertise();
                    element.ID = model.ID;
                }
                else
                    element = (from u in entities.Advertise
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.Name = model.Name == null ? string.Empty : model.Name;
                element.ImageLink = model.ImageLink == null ? string.Empty : model.ImageLink;
                element.BigImageLink = model.BigImageLink == null ? string.Empty : model.BigImageLink;
                element.DateTime = model.DateTime == null ? string.Empty : model.DateTime;
                element.Seq = model.Seq;
                element.ProjectID = project.ID;
                element.Effective = model.Effective;

                if (model.IsNew)
                    entities.Advertise.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("Advertise");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult AdvertiseDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.Advertise
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个广告！" });
            }
            entities.Advertise.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("Advertise");
        }

        public ActionResult AdvertiseEffective(Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.Advertise
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个广告！" });
            }

            gameType.Effective = !gameType.Effective;
            entities.SaveChanges();
            return this.RedirectToAction("Advertise");
        }

        public ActionResult Push()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            PushModel model = new PushModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.Push
                          orderby u.DateTime descending
                          select u).ToList();

            return View(model);
        }

        public ActionResult PushEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            PushEditModel model = new PushEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();
            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.Push
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个推送！" });
                }

                model.Title = element.Title;
                model.Content = element.Content;
                model.DateTime = element.DateTime;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult PushEdit(PushEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            if (ModelState.IsValid)
            {

                Push element = null;
                if (model.IsNew)
                {
                    element = new Push();
                    element.ID = model.ID;
                    element.DateTime = DateTime.Now;
                }
                else
                    element = (from u in entities.Push
                               where u.ID == model.ID
                               select u).SingleOrDefault();


                element.Title = model.Title == null ? string.Empty : model.Title;
                element.Content = model.Content == null ? string.Empty : model.Content;

                if (model.IsNew)
                    entities.Push.AddObject(element);



                System.Net.WebClient client = new System.Net.WebClient();
                System.Net.NetworkCredential credential = new System.Net.NetworkCredential("admin", "admin");
                credential.Domain = "www.itequan.com";
                client.Credentials = credential;
                System.Collections.Specialized.NameValueCollection postVars = new System.Collections.Specialized.NameValueCollection();
                postVars.Add("broadcast", "A");
                postVars.Add("title", element.Title);
                postVars.Add("message", element.Content);
                postVars.Add("uri", "www.itequan.com");
                try
                {
                    var value = client.UploadValues("http://www.itequan.com:8080/notification.do", "POST", postVars);
                    //下面都没用啦，就上面一句话就可以了
                    entities.SaveChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                }



                return this.RedirectToAction("Push");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult PushDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.Push
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个推送！" });
            }
            entities.Push.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("Push");
        }

        public ActionResult Password()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            PasswordModel model = new PasswordModel();
            GameCodeEntities entities = new GameCodeEntities();

            var systemData = (from s in entities.SystemData
                              where s.Name.Trim() == "Password"
                              select s).SingleOrDefault();
            if (systemData == null)
                model.Password = string.Empty;
            else
                model.Password = systemData.Value.Trim();

            systemData = (from s in entities.SystemData
                          where s.Name.Trim() == "SearchDefault"
                          select s).SingleOrDefault();
            if (systemData == null)
                model.SearchDefault = string.Empty;
            else
                model.SearchDefault = systemData.Value.Trim();

            return View(model);
        }

        [HttpPost]
        public ActionResult Password(PasswordModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            if (model.Password == null)
                model.Password = string.Empty;
            if (model.SearchDefault == null)
                model.SearchDefault = string.Empty;

            var systemData = (from s in entities.SystemData
                              where s.Name.Trim() == "Password"
                              select s).SingleOrDefault();
            if (systemData == null)
            {
                systemData = new SystemData();
                systemData.Name = "Password";
                entities.SystemData.AddObject(systemData);
            }
            systemData.Value = model.Password;

            systemData = (from s in entities.SystemData
                          where s.Name.Trim() == "SearchDefault"
                          select s).SingleOrDefault();
            if (systemData == null)
            {
                systemData = new SystemData();
                systemData.Name = "SearchDefault";
                entities.SystemData.AddObject(systemData);
            }
            systemData.Value = model.SearchDefault;


            entities.SaveChanges();

            return this.RedirectToAction("Message", new { message = "保存成功！" });

        }

        public ActionResult Backup()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            BackupModel model = new BackupModel();

            return View(model);

        }

        [HttpPost]
        public ActionResult Backup(BackupModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            Type sqlServerType = Type.GetTypeFromProgID("sqldmo.SQLServer");
            sqldmo.SQLServer srv = (sqldmo.SQLServer)Activator.CreateInstance(sqlServerType);

            string server = ConfigurationManager.AppSettings["Server"].ToString();
            string user = ConfigurationManager.AppSettings["User"].ToString();
            string password = ConfigurationManager.AppSettings["Password"].ToString();



            Type backupType = Type.GetTypeFromProgID("sqldmo.Backup");
            sqldmo.Backup backup = (sqldmo.Backup)Activator.CreateInstance(backupType);

            try
            {
                srv.Connect(server, user, password);

                backup.Action = 0;
                backup.Initialize = true;
                string fileName = string.Format("{0}.bak", DateTime.Now.ToString("yyyy-MM-dd"));
                backup.Files = Server.MapPath(string.Format("/Temp/{0}", fileName));
                backup.Database = "GameCode";
                backup.SQLBackup(srv);

                FileStream stream = new FileStream(backup.Files, FileMode.Open, FileAccess.Read);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                stream.Close();

                System.IO.File.Delete(backup.Files);
                return File(b, "application/octet-stream", fileName);

            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { message = ex.Message });
            }
            finally
            {
                srv.DisConnect();
            }
        }

        public ActionResult Restore()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            RestoreModel model = new RestoreModel();

            return View(model);

        }

        [HttpPost]
        public ActionResult Restore(HttpPostedFileBase file)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            Type sqlServerType = Type.GetTypeFromProgID("sqldmo.SQLServer");
            sqldmo.SQLServer srv = (sqldmo.SQLServer)Activator.CreateInstance(sqlServerType);

            string server = ConfigurationManager.AppSettings["Server"].ToString();
            string user = ConfigurationManager.AppSettings["User"].ToString();
            string password = ConfigurationManager.AppSettings["Password"].ToString();

            string fileName = string.Format("{0}.bak", DateTime.Now.ToString("yyyy-MM-dd"));
            string fullFileName = Server.MapPath(string.Format("/Temp/{0}", fileName));
            file.SaveAs(fullFileName);
            try
            {
                srv.Connect(server, user, password);
                sqldmo.QueryResults qr = srv.EnumProcesses(-1);

                int icolpidnum = -1;
                int icoldbname = -1;
                for (int i = 1; i <= qr.Columns; i++)
                {
                    string strname = qr.get_ColumnName(i);
                    if (strname.ToUpper().Trim() == "SPID")
                    {
                        icolpidnum = i;
                    }
                    else if (strname.ToUpper().Trim() == "DBNAME")
                    {
                        icoldbname = i;
                    }
                    if (icolpidnum != -1 && icoldbname != -1)
                        break;
                }

                for (int i = 1; i <= qr.Rows; i++)
                {
                    int lpid = qr.GetColumnLong(i, icolpidnum);
                    string strdbname = qr.GetColumnString(i, icoldbname);
                    if (strdbname.ToUpper() == "GAMECODE")
                        srv.KillProcess(lpid);
                }

                Type restoreType = Type.GetTypeFromProgID("sqldmo.Restore");
                sqldmo.Restore res = (sqldmo.Restore)Activator.CreateInstance(restoreType);
                res.Action = 0;
                res.Files = fullFileName;

                res.Database = "GameCode";
                res.ReplaceDatabase = true;
                res.SQLRestore(srv);

                return RedirectToAction("Message", new { message = "数据库还原成功！" });

            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { message = ex.Message });
            }
            finally
            {
                System.IO.File.Delete(fullFileName);
                srv.DisConnect();
            }
        }

        public ActionResult DeviceReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            DeviceReportModel model = new DeviceReportModel();
            model.CycleList = new List<string>() { "日", "周", "月" };
            model.Cycle = "日";
            model.EndDate = DateTime.Now;
            model.StartDate = DateTime.Now.AddMonths(-1);

            return View(model);
        }

        [HttpPost]
        public ActionResult DeviceReport(DeviceReportModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            GameCodeEntities entities = new GameCodeEntities();

            DateTime dateTime = new DateTime(model.StartDate.Year, model.StartDate.Month, model.StartDate.Day);
            DateTime endDateTime = new DateTime(model.EndDate.Year, model.EndDate.Month, model.EndDate.Day);
            model.List = new List<DeviceReportItem>();
            model.CycleList = new List<string>() { "日", "周", "月" };
            while (dateTime <= endDateTime)
            {
                DeviceReportItem item = new DeviceReportItem();
                DateTime sStartDateTime = dateTime;
                DateTime sEndDateTime = DateTime.MaxValue;
                switch (model.Cycle)
                {
                    case "日":
                        sEndDateTime = dateTime.AddDays(1).AddMilliseconds(-5);
                        item.日期 = sStartDateTime.ToString("yyyy-MM-dd");
                        dateTime = dateTime.AddDays(1);
                        break;
                    case "周":
                        sEndDateTime = dateTime.AddDays(8).AddMilliseconds(-5);
                        if (sEndDateTime > endDateTime)
                            sEndDateTime = endDateTime.AddDays(1).AddMilliseconds(-5);
                        item.日期 = string.Format("{0} ~ {1}", sStartDateTime.ToString("yyyy-MM-dd"), sEndDateTime.ToString("yyyy-MM-dd"));
                        dateTime = dateTime.AddDays(7);
                        break;
                    case "月":
                        sEndDateTime = dateTime.AddMonths(1).AddDays(1).AddMilliseconds(-5);
                        if (sEndDateTime > endDateTime)
                            sEndDateTime = endDateTime.AddDays(1).AddMilliseconds(-5);
                        item.日期 = string.Format("{0} ~ {1}", sStartDateTime.ToString("yyyy-MM-dd"), sEndDateTime.ToString("yyyy-MM-dd"));
                        dateTime = dateTime.AddMonths(1);
                        break;
                }

                item.新增安卓机 = (from d in entities.Device
                              where d.InstallDate >= sStartDateTime &&
                                    d.InstallDate <= sEndDateTime &&
                                    d.Type == "Android"
                              select d).Count();
                item.新增苹果机 = (from d in entities.Device
                              where d.InstallDate >= sStartDateTime &&
                                    d.InstallDate <= sEndDateTime &&
                                    (d.Type == "IPhone" || d.Type == "IPad")
                              select d).Count();
                item.活跃安卓机 = (from l in entities.AccessLog
                              where l.DateTime >= sStartDateTime &&
                                     l.DateTime <= sEndDateTime &&
                                     l.Device.Type == "Android"
                              select l.DeviceID).Distinct().Count();
                item.新增苹果机 = (from l in entities.AccessLog
                              where l.DateTime >= sStartDateTime &&
                                     l.DateTime <= sEndDateTime &&
                                     (l.Device.Type == "IPhone" || l.Device.Type == "IPad")
                              select l.DeviceID).Distinct().Count();

                model.List.Add(item);
            }

            TempData["Reoprt"] = model;
            if (model.IsExport)
                return RedirectToAction("DeviceReportReport", "Admin");
            else
            {
                return View(model);
            }
        }

        public ActionResult DeviceReportReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            DeviceReportModel model = (DeviceReportModel)TempData["Reoprt"];
            RptDeviceReport report = new RptDeviceReport();
            report.Source.DataSource = model.List;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToXls(stream);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                return File(b, "application/octet-stream", "设备统计.xls");
            }

            return View(model);
        }

        public ActionResult AdvancedReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            AdvancedReportModel model = new AdvancedReportModel();
            model.EndDate = DateTime.Now;
            model.StartDate = DateTime.Now.AddMonths(-1);

            return View(model);
        }

        [HttpPost]
        public ActionResult AdvancedReport(AdvancedReportModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            GameCodeEntities entities = new GameCodeEntities();

            DateTime dateTime = new DateTime(model.StartDate.Year, model.StartDate.Month, model.StartDate.Day);
            DateTime endDateTime = new DateTime(model.EndDate.Year, model.EndDate.Month, model.EndDate.Day);
            model.List = new List<AdvancedReportItem>();
            while (dateTime <= endDateTime)
            {
                AdvancedReportItem item = new AdvancedReportItem();
                DateTime sStartDateTime = dateTime;
                DateTime sEndDateTime = DateTime.MaxValue;

                sEndDateTime = dateTime.AddDays(1).AddMilliseconds(-5);
                item.日期 = sStartDateTime.ToString("yyyy-MM-dd");
                dateTime = dateTime.AddDays(1);
                

                item.新增用户 = (from d in entities.Device
                             where d.InstallDate >= sStartDateTime &&
                                   d.InstallDate <= sEndDateTime
                             select d).Count();
                item.活跃用户 = (from l in entities.AccessLog
                             where l.DateTime >= sStartDateTime &&
                                    l.DateTime <= sEndDateTime
                             select l.DeviceID).Distinct().Count();

                item.总点击 = (from d in entities.HitLog
                            where d.DateTime >= sStartDateTime &&
                                  d.DateTime <= sEndDateTime &&
                                  d.SourceType == "Project"
                            select d).Count();
                item.总发码 = (from d in entities.Code
                            where d.DeviceID != null &&
                                  d.FetchDate >= sStartDateTime &&
                                   d.FetchDate <= sEndDateTime
                            select d).Count();

                model.List.Add(item);
            }

            TempData["Reoprt"] = model;
            if (model.IsExport)
                return RedirectToAction("AdvancedReportReport", "Admin");
            else
            {
                return View(model);
            }
        }

        public ActionResult AdvancedReportReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            AdvancedReportModel model = (AdvancedReportModel)TempData["Reoprt"];
            RptAdvancedReport report = new RptAdvancedReport();
            report.Source.DataSource = model.List;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToXls(stream);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                return File(b, "application/octet-stream", "综合统计.xls");
            }

            return View(model);
        }

        public ActionResult ProjectReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            ProjectReportModel model = new ProjectReportModel();
            //model.CycleList = new List<string>() { "日", "周", "月" };
            //model.Cycle = "日";
            model.EndDate = DateTime.Now;
            model.StartDate = DateTime.Now.AddMonths(-1);

            return View(model);
        }

        [HttpPost]
        public ActionResult ProjectReport(ProjectReportModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            GameCodeEntities entities = new GameCodeEntities();

            DateTime dateTime = new DateTime(model.StartDate.Year, model.StartDate.Month, model.StartDate.Day);
            DateTime endDateTime = new DateTime(model.EndDate.Year, model.EndDate.Month, model.EndDate.Day);
            model.List = new List<ProjectReportItem>();
            //model.CycleList = new List<string>() { "日", "周", "月" };
            DateTime sStartDateTime = model.StartDate;
            DateTime sEndDateTime = model.EndDate.AddDays(1).AddMilliseconds(-5);

            var projectList = (from u in entities.GameProject
                               orderby u.Seq, u.GameName
                               select u).ToList();

            foreach (var project in projectList)
            {
                ProjectReportItem item = new ProjectReportItem();
                item.项目编号 = project.ProjectNr.Trim();
                item.游戏名称 = project.GameName == null ? string.Empty : project.GameName.Trim();
                item.项目名称 = project.ProjectName == null ? string.Empty : project.ProjectName.Trim();

                item.点击次数 = (from d in entities.HitLog
                             where d.DateTime >= sStartDateTime &&
                                   d.DateTime <= sEndDateTime &&
                                   d.SourceID == project.ID &&
                                   d.SourceType == "Project"
                             select d).Count();
                item.领取数量 = (from d in entities.Code
                             where d.DeviceID != null &&
                                   d.FetchDate >= sStartDateTime &&
                                    d.FetchDate <= sEndDateTime &&
                                    d.ProjectID == project.ID
                             select d).Count();

                model.List.Add(item);
            }

            TempData["Reoprt"] = model;
            if (model.IsExport)
                return RedirectToAction("ProjectReportReport", "Admin");
            else
            {
                return View(model);
            }
        }

        public ActionResult ProjectReportReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            ProjectReportModel model = (ProjectReportModel)TempData["Reoprt"];
            RptProjectReport report = new RptProjectReport();
            report.Source.DataSource = model.List;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToXls(stream);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                return File(b, "application/octet-stream", "项目统计.xls");
            }

            return View(model);
        }

        public ActionResult AdvertiseReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            AdvertiseReportModel model = new AdvertiseReportModel();
            //model.CycleList = new List<string>() { "日", "周", "月" };
            //model.Cycle = "日";
            model.EndDate = DateTime.Now;
            model.StartDate = DateTime.Now.AddMonths(-1);

            return View(model);
        }

        [HttpPost]
        public ActionResult AdvertiseReport(AdvertiseReportModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            GameCodeEntities entities = new GameCodeEntities();

            DateTime dateTime = new DateTime(model.StartDate.Year, model.StartDate.Month, model.StartDate.Day);
            DateTime endDateTime = new DateTime(model.EndDate.Year, model.EndDate.Month, model.EndDate.Day);
            model.List = new List<AdvertiseReportItem>();
            //model.CycleList = new List<string>() { "日", "周", "月" };
            DateTime sStartDateTime = model.StartDate;
            DateTime sEndDateTime = model.EndDate.AddDays(1).AddMilliseconds(-5);

            var advertiseList = (from u in entities.Advertise
                                 orderby u.Effective descending, u.Seq
                                 select u).ToList();

            foreach (var advertise in advertiseList)
            {
                AdvertiseReportItem item = new AdvertiseReportItem();
                item.项目编号 = advertise.GameProject.ProjectNr.Trim();
                item.游戏名称 = advertise.GameProject.GameName == null ? string.Empty : advertise.GameName.Trim();
                item.项目名称 = advertise.GameProject.ProjectName == null ? string.Empty : advertise.ProjectName.Trim();
                item.广告名称 = advertise.Name == null ? string.Empty : advertise.Name.Trim();
                item.点击次数 = (from d in entities.HitLog
                             where d.DateTime >= sStartDateTime &&
                                   d.DateTime <= sEndDateTime &&
                                   d.SourceID == advertise.ID &&
                                   d.SourceType == "Advertise"
                             select d).Count();

                if (item.点击次数 == 0 && !advertise.Effective)
                    continue;

                model.List.Add(item);
            }

            TempData["Reoprt"] = model;
            if (model.IsExport)
                return RedirectToAction("AdvertiseReportReport", "Admin");
            else
            {
                return View(model);
            }
        }

        public ActionResult AdvertiseReportReport()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");
            AdvertiseReportModel model = (AdvertiseReportModel)TempData["Reoprt"];
            RptAdvertiseReport report = new RptAdvertiseReport();
            report.Source.DataSource = model.List;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToXls(stream);
                byte[] b = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(b, 0, b.Length);
                return File(b, "application/octet-stream", "广告统计.xls");
            }

            return View(model);
        }

        public ActionResult NewArea()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            NewAreaModel model = new NewAreaModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.NewArea
                          orderby u.Effective descending, u.Seq, u.GameProject.GameName
                          select u).ToList();

            return View(model);
        }

        public ActionResult NewAreaEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            NewAreaEditModel model = new NewAreaEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.NewArea
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个新区资信！" });
                }

                model.Operator = element.Operator;
                model.ServerName = element.ServerName;
                model.StartDate = element.StartDate;
                model.Effective = element.Effective;
                model.Seq = element.Seq;
                model.ID = element.ID;
                model.ProjectNr = element.GameProject.ProjectNr;

            }

            return View(model);
        }

        [HttpPost]
        public ActionResult NewAreaEdit(NewAreaEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var project = (from p in entities.GameProject
                           where p.ProjectNr == model.ProjectNr
                           select p).SingleOrDefault();
            if (project == null)
                ModelState.AddModelError("ProjectNr", "没有对应的项目");

            if (ModelState.IsValid)
            {

                NewArea element = null;
                if (model.IsNew)
                {
                    element = new NewArea();
                    element.ID = model.ID;
                }
                else
                    element = (from u in entities.NewArea
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.ServerName = model.ServerName == null ? string.Empty : model.ServerName;
                element.Operator = model.Operator == null ? string.Empty : model.Operator;
                element.StartDate = model.StartDate == null ? string.Empty : model.StartDate;
                element.Seq = model.Seq;
                element.ProjectID = project.ID;
                element.Effective = model.Effective;

                if (model.IsNew)
                    entities.NewArea.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("NewArea");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult NewAreaDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.NewArea
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个新区资信！" });
            }
            entities.NewArea.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("NewArea");
        }

        public ActionResult NewAreaEffective(Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.NewArea
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个新区资信！" });
            }

            gameType.Effective = !gameType.Effective;
            entities.SaveChanges();
            return this.RedirectToAction("NewArea");
        }

        public ActionResult NewAreaDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.NewArea
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个新区资信！" });
            }
            var list = (from u in entities.NewArea
                        where u.Seq > gameType.Seq && u.Effective == gameType.Effective
                        orderby u.Effective descending, u.Seq, u.GameProject.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("NewArea");
        }

        public ActionResult NewAreaUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.NewArea
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个新区资信！" });
            }
            var list = (from u in entities.NewArea
                        where u.Seq < gameType.Seq && u.Effective == gameType.Effective
                        orderby u.Effective descending, u.Seq, u.GameProject.GameName
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("NewArea");
        }

        public ActionResult AndroidApp()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            AndroidAppModel model = new AndroidAppModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.AndriodApp
                          orderby u.Version descending
                          select u).ToList();

            return View(model);
        }

        public ActionResult AndroidAppEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            AndroidAppEditModel model = new AndroidAppEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.AndriodApp
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个安卓应用！" });
                }

                model.Version = element.Version;
                model.Link = element.Link;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult AndroidAppEdit(AndroidAppEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            if (ModelState.IsValid)
            {

                AndriodApp element = null;
                if (model.IsNew)
                {
                    element = new AndriodApp();
                    element.ID = model.ID;
                }
                else
                    element = (from u in entities.AndriodApp
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.Version = model.Version == null ? string.Empty : model.Version;
                element.Link = model.Link == null ? string.Empty : model.Link;

                if (model.IsNew)
                    entities.AndriodApp.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("AndroidApp");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult AndroidAppDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.AndriodApp
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个安卓应用！" });
            }
            entities.AndriodApp.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("AndroidApp");
        }

        public ActionResult Banner()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BannerModel model = new BannerModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.PageElement
                          where u.Type == "Banner"
                          orderby u.Seq, u.Content
                          select new Banner()
                          {
                              ID = u.ID,
                              Name = u.Content,
                              Link = u.Link,
                              ImageLink = u.ImageLink,
                              Seq = u.Seq
                          }).ToList();

            return View(model);
        }

        public ActionResult BannerEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            BannerEditModel model = new BannerEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.PageElement
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个滚动图！" });
                }

                model.Name = element.Content;
                model.ImageLink = element.ImageLink;
                model.Link = element.Link;
                model.Seq = element.Seq;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult BannerEdit(BannerEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            if (ModelState.IsValid)
            {

                PageElement element = null;
                if (model.IsNew)
                {
                    element = new PageElement();
                    element.ID = model.ID;
                    element.Type = "Banner";
                }
                else
                    element = (from u in entities.PageElement
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.Content = model.Name == null ? string.Empty : model.Name;
                element.ImageLink = model.ImageLink == null ? string.Empty : model.ImageLink;
                element.Link = model.Link == null ? string.Empty : model.Link;
                element.Seq = model.Seq;

                if (model.IsNew)
                    entities.PageElement.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("Banner");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult BannerDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.PageElement
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个滚动图！" });
            }
            entities.PageElement.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("Banner");
        }

        public ActionResult BannerDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个滚动图！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq > gameType.Seq &&
                              u.Type == "Banner"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("Banner");
        }

        public ActionResult BannerUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个滚动图！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq < gameType.Seq &&
                              u.Type == "Banner"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("Banner");
        }

        public ActionResult PageSetting()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            PageSettingModel model = new PageSettingModel();

            GameCodeEntities entities = new GameCodeEntities();
            var element = (from u in entities.SystemData
                           where u.Name == "IPhoneDownload"
                           select u).SingleOrDefault();
            if (element != null)
            {
                model.IPhoneDownload = element.Value;
            }

            element = (from u in entities.SystemData
                       where u.Name == "CodeLink"
                       select u).SingleOrDefault();
            if (element != null)
            {
                model.CodeLink = element.Value;
            }

            element = (from u in entities.SystemData
                       where u.Name == "Footer"
                       select u).SingleOrDefault();
            if (element != null)
            {
                model.Footer = element.Value;
            }

            return View(model);
        }


        [HttpPost]
        public ActionResult PageSetting(PageSettingModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.SystemData
                               where u.Name == "IPhoneDownload"
                               select u).SingleOrDefault();
                if (element != null)
                {
                    element.Value = model.IPhoneDownload;
                }
                else
                {
                    element = new SystemData();
                    element.Name = "IPhoneDownload";
                    element.Value = model.IPhoneDownload;

                    entities.SystemData.AddObject(element);
                }

                element = (from u in entities.SystemData
                           where u.Name == "CodeLink"
                           select u).SingleOrDefault();
                if (element != null)
                {
                    element.Value = model.CodeLink;
                }
                else
                {
                    element = new SystemData();
                    element.Name = "CodeLink";
                    element.Value = model.CodeLink;

                    entities.SystemData.AddObject(element);
                }

                element = (from u in entities.SystemData
                           where u.Name == "Footer"
                           select u).SingleOrDefault();
                if (element != null)
                {
                    element.Value = model.Footer;
                }
                else
                {
                    element = new SystemData();
                    element.Name = "Footer";
                    element.Value = model.Footer;

                    entities.SystemData.AddObject(element);
                }

                entities.SaveChanges();

                return this.RedirectToAction("Message", new { message = "修改成功" });
            }
            return View(model);
        }

        public ActionResult Article(string type)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            ArticleModel model = new ArticleModel();
            GameCodeEntities entities = new GameCodeEntities();
            var article = (from a in entities.SystemArticle
                           where a.Type == type
                           select a).SingleOrDefault();
            if (article != null)
                model.Content = article.Content;

            switch (type)
            {
                case "Product":
                    model.Caption = "产品页文章";
                    break;
                case "Download":
                    model.Caption = "下载页文章";
                    break;
                case "Teamwork":
                    model.Caption = "商务合作页文章";
                    break;
                case "Mobile":
                    model.Caption = "手机浏览页文章";
                    break;
            }


            return View(model);
        }

        [HttpPost]
        public ActionResult Article(ArticleModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            if (ModelState.IsValid)
            {
                GameCodeEntities entities = new GameCodeEntities();
                var article = (from a in entities.SystemArticle
                               where a.Type == model.Type
                               select a).SingleOrDefault();
                if (article == null)
                {
                    article = new SystemArticle();
                    article.ID = Guid.NewGuid();
                    article.Name = article.Type = model.Type;
                    article.DateTime = DateTime.Now;
                    entities.SystemArticle.AddObject(article);
                }

                article.Content = model.Content;

                entities.SaveChanges();

                return this.RedirectToAction("Message", new { message = "修改成功" });

            }

            switch (model.Type)
            {
                case "Product":
                    model.Caption = "产品页文章";
                    break;
                case "Download":
                    model.Caption = "下载页文章";
                    break;
                case "Teamwork":
                    model.Caption = "商务合作页文章";
                    break;
                case "Mobile":
                    model.Caption = "手机浏览页文章";
                    break;
            }


            return View(model);
        }

        public ActionResult FriendLink()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            FriendLinkModel model = new FriendLinkModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.PageElement
                          where u.Type == "FriendLink"
                          orderby u.Seq, u.Content
                          select new FriendLink()
                          {
                              ID = u.ID,
                              Name = u.Content,
                              Link = u.Link,
                              ImageLink = u.ImageLink,
                              Seq = u.Seq
                          }).ToList();

            return View(model);
        }

        public ActionResult FriendLinkEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            FriendLinkEditModel model = new FriendLinkEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.PageElement
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个友情链接！" });
                }

                model.Name = element.Content;
                model.ImageLink = element.ImageLink;
                model.Link = element.Link;
                model.Seq = element.Seq;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult FriendLinkEdit(FriendLinkEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            if (ModelState.IsValid)
            {

                PageElement element = null;
                if (model.IsNew)
                {
                    element = new PageElement();
                    element.ID = model.ID;
                    element.Type = "FriendLink";
                }
                else
                    element = (from u in entities.PageElement
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.Content = model.Name == null ? string.Empty : model.Name;
                element.ImageLink = model.ImageLink == null ? string.Empty : model.ImageLink;
                element.Link = model.Link == null ? string.Empty : model.Link;
                element.Seq = model.Seq;

                if (model.IsNew)
                    entities.PageElement.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("FriendLink");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult FriendLinkDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.PageElement
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个友情链接！" });
            }
            entities.PageElement.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("FriendLink");
        }

        public ActionResult FriendLinkDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个友情链接！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq > gameType.Seq &&
                              u.Type == "FriendLink"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("FriendLink");
        }

        public ActionResult FriendLinkUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个友情链接！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq < gameType.Seq &&
                              u.Type == "FriendLink"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("FriendLink");
        }

        public ActionResult News()
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            NewsModel model = new NewsModel();

            GameCodeEntities entities = new GameCodeEntities();
            model.List = (from u in entities.PageElement
                          where u.Type == "News"
                          orderby u.Seq
                          select new News()
                          {
                              ID = u.ID,
                              Content = u.Content,
                              Seq = u.Seq
                          }).ToList();

            return View(model);
        }

        public ActionResult NewsEdit(Guid? id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            NewsEditModel model = new NewsEditModel();

            if (id == null)
            {
                model.IsNew = true;
                model.ID = Guid.NewGuid();

            }
            else
            {
                GameCodeEntities entities = new GameCodeEntities();
                var element = (from u in entities.PageElement
                               where u.ID == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个消息！" });
                }

                model.Content = element.Content;
                model.Seq = element.Seq;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult NewsEdit(NewsEditModel model)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();

            if (ModelState.IsValid)
            {

                PageElement element = null;
                if (model.IsNew)
                {
                    element = new PageElement();
                    element.ID = model.ID;
                    element.Type = "News";
                    element.ImageLink = string.Empty;
                    element.Link = string.Empty;
                }
                else
                    element = (from u in entities.PageElement
                               where u.ID == model.ID
                               select u).SingleOrDefault();



                element.Content = model.Content == null ? string.Empty : model.Content;
                element.Seq = model.Seq;

                if (model.IsNew)
                    entities.PageElement.AddObject(element);

                entities.SaveChanges();

                return this.RedirectToAction("News");
            }
            model.IsReturn = true;
            return View(model);
        }

        public ActionResult NewsDelete(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var user = (from u in entities.PageElement
                        where u.ID == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个消息！" });
            }
            entities.PageElement.DeleteObject(user);
            entities.SaveChanges();

            return this.RedirectToAction("News");
        }

        public ActionResult NewsDown(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个消息！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq > gameType.Seq &&
                              u.Type == "News"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[0];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("News");
        }

        public ActionResult NewsUp(Guid id)
        {
            if (!object.Equals(Session["gc-AdminLogin"], true))
                return this.RedirectToAction("Login", "Admin");

            GameCodeEntities entities = new GameCodeEntities();
            var gameType = (from u in entities.PageElement
                            where u.ID == id
                            select u).SingleOrDefault();
            if (gameType == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个消息！" });
            }
            var list = (from u in entities.PageElement
                        where u.Seq < gameType.Seq &&
                              u.Type == "News"
                        orderby u.Seq, u.Content
                        select u).ToList();
            if (list.Count != 0)
            {
                var nextGameType = list[list.Count - 1];
                int temp = nextGameType.Seq;
                nextGameType.Seq = gameType.Seq;
                gameType.Seq = temp;

                entities.SaveChanges();
            }


            return this.RedirectToAction("News");
        }
    }
}
